# -*- coding: utf-8 -*-
import json
import traceback
import uuid

from concurrent.futures import ThreadPoolExecutor

from flask import Flask, jsonify, request
from pageMethod.xhsLogin import userinfo
from pageMethod.xhsLogin import Login
from pageMethod.xhsSendcode import sendCode
from pageMethod.xhsSubmit import PostNotes, noteStats
from public.config import log, drivers

executor = ThreadPoolExecutor(100)

app = Flask(__name__)
# app.config['JSONIFY_MIMETYPE'] = "application/json;charset=utf-8"  # 指定浏览器渲染的文件类型，和解码格式；
# app.config['JSON_AS_ASCII'] = False





@app.route("/xhsSendCode", methods=['POST'])
def sendcode():
    tid = str(uuid.uuid4())
    try:
        data = request.json
        log.info(f"/xhsSendCode入参:{data}", tid)
        mobile = data.get('mobile')
        executor.submit(sendCode, mobile, tid)
        return jsonify({
            "code": 0,
            "msg": "",
            "data": {},
            "tid": tid
        })
    except BaseException as e:
        log.error(f"/xhsSendCode系统错误:{e}", tid)
        return jsonify({
            "code": 500,
            "msg": "系统错误",
            "tid": tid})


@app.route("/xhslogin", methods=['POST'])
def login():
    tid = str(uuid.uuid4())
    try:
        data = request.json
        log.info(f"/xhslogin入参:{data}", tid)
        code = data.get("code")
        mobile = data.get("mobile")
        driver = drivers.get(mobile)
        log.info(f"获取driver:{driver}", tid)
        if not driver:
            return jsonify({"code": 1, "msg": "登录失败，请退出重试", "data": {}})
        results = Login(driver, code, mobile, tid)
        if len(results) == 2:
            cookies = results[0]
            userInfo = results[1]
            userInfo = json.loads(userInfo)
            userName = userInfo.get('data').get("userName")
            userAvatar = userInfo.get('data').get("userAvatar")
            redId = userInfo.get('data').get("redId")
            del drivers[mobile]
            return jsonify({
                "code": 0,
                "msg": "登录成功",
                "data": {
                    "cookies": cookies,
                    "avatar": userAvatar,
                    "userName": userName,
                    "redId": redId
                },
                "tid": tid
            })
        else:
            msg = results
            return jsonify({
                "code": -1,
                "msg": msg,
                "tid": tid})

    except BaseException as e:
        log.error(f"/xhslogin系统错误:{e}", tid)
        return jsonify({
            "code": 500,
            "msg": "系统错误，请退出重试",
            "tid": tid})

@app.route("/xhsPublish", methods=['POST'])
def publish():
    tid = str(uuid.uuid4())
    try:
        data = request.json
        log.info(f"/xhsPublish入参:{data}", tid)
        mobile = data.get("mobile")
        ykId = data.get("ykId")
        cookies = data.get("cookies")
        title = data.get("title")
        content = data.get("content")
        tags = data.get("tags")
        images = data.get("images")
        executor.submit(PostNotes, mobile, ykId, cookies, title, content, tags, images, tid)
        return jsonify({
        "code": 0,
        "msg": "",
        "data": {
            "status": 0,
        },
        "tid": tid
    })
    except BaseException as e:
        log.error(f"/xhsPublish系统错误:{e}", tid)
        return jsonify({
            "code": 500,
            "msg": "系统错误",
            "tid": tid})
@app.route("/xhsUserInfo", methods=['POST'])
def UserInfo():
    tid = str(uuid.uuid4())
    try:
        data = request.json
        log.info(f"/xhsUserInfo入参:{data}", tid)
        mobile = data.get("mobile")
        cookies = data.get("cookies")
        userInfo = userinfo(cookies, mobile, tid)
        userInfo = json.loads(userInfo)
        if not userInfo.get("success"):
            return jsonify({
        "code": -1,
        "msg": userInfo.get("msg"),
                "tid": tid})

        else:
            return jsonify({
                "code": 0,
                "msg": "登录未过期",
            "tid": tid})
    except:
        msg = traceback.format_exc()
        log.error(f"/xhsUserInfo系统错误:{msg}", tid)
        return jsonify({
            "code": 500,
            "msg": "系统错误",
            "tid": tid})

@app.route("/xhsNoteStats", methods=['POST'])
def NoteStats():
    data = request.json
    tid = str(uuid.uuid4())
    try:
        log.info(f"/xhsNoteStats入参:{data}", tid)
        mobile = data.get("mobile")
        cookies = data.get("cookies")
        xhsId = data.get("xhsId")
        statsData = noteStats(cookies, mobile, tid)
        statsData = json.loads(statsData)
        if not statsData.get("success"):
            return jsonify({
        "code": -1,
        "msg": statsData.get("msg")})
        else:
            if statsData.get("data"):
                note_infos = statsData.get("data").get("note_infos")
                for note_info in note_infos:
                    if note_info.get("id") == xhsId:
                        viewCount = note_info.get("read")
                        likeCount = note_info.get("like")
                        collectionCount = note_info.get("fav")
                        commentCount = note_info.get("comment")

                        return jsonify({
                                "code": 0,
                                "msg": "",
                                "data": {

                                    "viewCount": viewCount,
                                    "likeCount": likeCount,
                                    "collectionCount": collectionCount,
                                    "commentCount": commentCount
                                },
                                    "tid": tid})
                return jsonify({
                                "code": -1,
                                "msg": f"找不到该xhsId:{xhsId}的数据",
                                "tid": tid})
            else:
                return jsonify({
                                "code": -1,
                                "msg": f"找不到该xhsId:{xhsId}的数据",
                                "tid": tid})
    except BaseException as e:
        log.error(f"/xhsNoteStats系统错误:{e}", tid)
        return jsonify({
            "code": 500,
            "msg": "系统错误",
            "tid": tid})


if __name__ == '__main__':

    app.run('0.0.0.0', 5009)
